// 自动调整碰撞器大小
import { _decorator, Component, UITransform, BoxCollider2D, Vec2, Size, Node } from 'cc'
const { ccclass } = _decorator

@ccclass('AutoResizeCollider')
export class AutoResizeCollider extends Component {
  private collider: BoxCollider2D | null = null
  private uiTransform: UITransform | null = null

  start() {
    this.collider = this.getComponent(BoxCollider2D)
    this.uiTransform = this.getComponent(UITransform)

    if (!this.collider || !this.uiTransform) {
      console.warn('需要挂载 BoxCollider2D 和 UITransform 组件')
      return
    }

    // 初始调整
    this.updateColliderSize()

    // 监听节点尺寸变化（Cocos3.7+ 支持）
    this.node.on(Node.EventType.SIZE_CHANGED, this.updateColliderSize, this)
  }

  updateColliderSize() {
    const width = this.uiTransform!.contentSize.width
    const height = this.uiTransform!.contentSize.height

    // 让碰撞盒大小与节点尺寸一致
    this.collider!.size = new Size(width, height)

    // 如果碰撞区域有偏移，可以设置 offset
    this.collider!.offset = new Vec2(0, 0)

    // 更新物理形状
    this.collider!.apply()
  }

  onDestroy() {
    this.node.off(Node.EventType.SIZE_CHANGED, this.updateColliderSize, this)
  }
}
